<template>
  <view class="drop-down-container">
    <view class="title-view hor-layout-center-all" @click="changeContentState">
      <view class="title-text" :class="{'display':state===1}">{{ title }}</view>
      <i class="iconfont arrow-icon" :class="{'display':state===1}">&#xe8f2;</i>
    </view>
    <view class="content-layout" :class="{'display':state===1}" @click="changeContentState">
      <view v-for="(item,index) in options" :key="index" class="list-item" @click="itemClick(item)">
        <view class="item-text" :class="{'select':selectValue===item.value}">{{ item.label }}</view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "drop-down",
  props: {
    value: {type: Number},
    options: {
      type: Array,
      default: () => {
        return [{value: 'c1', label: '数据1'}, {value: 'c2', label: '数据2'}]
      }
    }
  },
  data() {
    return {
      state: 0,//0：折叠，1：展开
      title: ''
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val, oldVal) {
        let selObj = this.options.find(o => o.value === val)
        this.title = selObj && selObj.label
      }
    }
  },
  computed: {
    selectValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      }
    }
  },
  methods: {
    changeContentState() {
      this.state = this.state === 0 ? 1 : 0
    },
    itemClick(item) {
      this.selectValue = item.value //1.先将值回传
      this.title = this.options.find(o => o.value === item.value).label
      this.$emit("change", item.value);//2.再通知父组件事件
    }
  }
}
</script>

<style scoped>
.drop-down-container {
  z-index: 1000;
  position: relative;
  width: 100%;
  height: 40px;
}

.title-view {
  position: relative;
  z-index: 1000;
  width: 100%;
  height: 40px;
  background: white;
  border-bottom: 1px solid #E4E4E4;
}

.title-text {
  font-size: 14px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #333333;
  transition: all 0.3s;
}

.title-text.display {
  color: #42B4AC;
}

.arrow-icon {
  color: #333333;
  transform: rotate(0deg);
  transition: all 0.3s;
}

.arrow-icon.display {
  color: #42B4AC;
  transform: rotate(180deg);
}

.content-layout {
  top: 40px;
  position: absolute;
  width: 100%;
  max-height: 0;
  overflow: hidden;
  background: transparent;
  transition: all 0.3s ease-out;
}

.content-layout.display {
  height: 800px;
  max-height: 800px;
  background: rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease-in;
}

.list-item {
  width: 100%;
  height: 36px;
  line-height: 36px;
  text-align: center;
  background: white;
  border-bottom: 1px solid #E4E4E4;
}

.item-text {
  font-size: 14px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #333333;
}

.item-text.select {
  color: #42B4AC;
}
</style>
